# python numpy实现k-近邻算法
import numpy as np
import operator as op

def createDataset():
    group=np.array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])
    labels=['A','A','B','B']
    return group,labels

def classify0(inX,dataset,labels,k):
    datasetSize=dataset.shape[0]

    # 计算距离
    diffMat=np.tile(inX,(datasetSize,1))-dataset
    sqDiffMat=diffMat**2
    sqDistances=sqDiffMat.sum(axis=1)
    distances=sqDistances**0.5

    # 
    sortedDistIndicies=distances.argsort()
    classCount={}
    for i in range(k):
        voteIlabel=labels[sortedDistIndicies[i]]
        # 选择距离最小的点
        classCount[voteIlabel]=classCount.get(voteIlabel,0)+1

    # 排序
    sortedClassConut=sorted(classCount.items(),key=op.itemgetter(1),reverse=True)
    return sortedClassConut[0][0]

group,labels=createDataset()
result=classify0([0,0],group,labels,3)
print('result : ',result)   # result :  B